<template>
  <el-dialog :model-value="visible" :draggable="true" title="多计量单位" width="40%">
    <el-form ref="erpUnitAttrFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="包装单位" prop="name">
        <el-select v-model="form.unitId">
          <el-option v-for="item in erpUnitList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="计量值" prop="name">
        <el-input v-model="form.attrNum" placeholder="只能是数字" />
      </el-form-item>
      <el-form-item label="标识" prop="name">
        <el-input v-model="form.remark" placeholder="例：500克/袋" />
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="erpUnitAttrList" @selection-change="handleSelectionChange" height="200px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规格名称" align="center" prop="unitName" />
      <el-table-column label="规格数量" align="center" prop="attrNum" />
      <el-table-column label="规格描述" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button v-hasPermi="['erp:erpUnitAttr:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button v-hasPermi="['erp:erpUnitAttr:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ErpUnitAttrForm, ErpUnitAttrQuery, ErpUnitAttrVO } from '@/api/erp/erpUnitAttr/types';
import { addErpUnitAttr, delErpUnitAttr, getErpUnitAttr, listErpUnitAttr, updateErpUnitAttr } from '@/api/erp/erpUnitAttr';
import { ErpUnitVO } from '@/api/erp/erpUnit/types';
import { listErpUnit } from '@/api/erp/erpUnit';

const props = defineProps({
  rowData: {
    type: Object,
    default: null
  },
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: null
  }
});
const emit = defineEmits(['update:modelValue', 'loadList']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const erpUnitAttrList = ref<ErpUnitAttrVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);
const erpUnitList = ref<ErpUnitVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const erpUnitAttrFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: ErpUnitAttrForm = {
  id: undefined,
  name: undefined,
  attrNum: undefined,
  unitId: props.formData.unitId,
  remark: undefined,
  productId: props.formData.id
};
const data = reactive<PageData<ErpUnitAttrForm, ErpUnitAttrQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: props.formData.id,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    attrNum: [{ required: true, message: '规格数量不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询多计量单位列表 */
const getList = async () => {
  loading.value = true;
  const res = await listErpUnitAttr(queryParams.value);
  erpUnitAttrList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 查询计量单位列表 */
const getUnitList = async () => {
  loading.value = true;
  const res = await listErpUnit();
  erpUnitList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  emit('update:modelValue', false);
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  erpUnitAttrFormRef.value?.resetFields();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: ErpUnitAttrVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 修改按钮操作 */
const handleUpdate = async (row?: ErpUnitAttrVO) => {
  reset();
  //TODO 要把这些值传到上面新增表格
  const _id = row?.id || ids.value[0];
  const res = await getErpUnitAttr(_id);
  Object.assign(form.value, res.data);
};

/** 提交按钮 */
const submitForm = () => {
  erpUnitAttrFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateErpUnitAttr(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addErpUnitAttr(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ErpUnitAttrVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除多计量单位编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delErpUnitAttr(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  getList();
  getUnitList();
});
</script>
